import { defineStore } from "pinia";
import * as icons from "@ant-design/icons-vue";
import { h } from "vue"; // 导入 h 函数
// import { useRoutesStore } from "@/store/index";
import { getMenuList } from "@/request/api/login/index";

const useMenu = defineStore("menu", {
  state: () => {
    return {
      menu: [],
      menuList: [],
      selectedKeys: [9999],
      openKeys: [],
      activeKey: 9999,
      menuTree: [],
      breadcrumb: ["首页"],
      onUseMenu: [
        {
          title: "首页",
          pid: "",
          path: "/home",
          key: 9999,
          iconString: "HomeOutlined",
          closable: false,
        },
      ],
    };
  },
  actions: {
    updateOnUseMenu(newVal) {
      this.onUseMenu = newVal;
    },
    updateSelectedKeys(newVal) {
      this.selectedKeys = newVal;
    },
    updateOpenKeys(newVal) {
      this.openKeys = newVal;
    },
    updateActiveKey(newVal) {
      this.activeKey = newVal;
    },
    updateOnBreadcrumb(newVal) {
      this.breadcrumb = newVal;
    },
    async handleMenuList() {
      try {
        const response = await getMenuList();
        if (response.code === 200) {
          this.menuList = response.data;
          this.menu = [
            {
              breadcrumbName: "首页",
              component: "@/views/home/index",
              description: "首页",
              icon: "HomeOutlined",
              id: 9999,
              isShow: 1,
              menuName: "首页",
              menuType: "C",
              orderNum: 0,
              path: "/",
              pid: null,
            },
            ...response.data,
          ];
          this.menu.forEach((item) => {
            item["breadcrumbName"] = item.menuName;
          });
        }
      } catch (error) {
        console.error("Failed to fetch menu list:", error);
      }
    },

    async arrToTree() {
      const getItem = (label, key, icon, children, path, orderNum) => {
        return {
          key,
          icon: () => h(icons[icon]),
          children,
          label,
          path,
          title: label,
          breadcrumbName: label,
          iconString: icon,
          order_num: orderNum,
        };
      };

      await this.handleMenuList();

      const handleMenuTree = (list) => {
        // 过滤并排序数据
        const data = list
          .filter((item) => item.menuType !== "F")
          .sort((a, b) => (a.order_num || 0) - (b.order_num || 0));

        const result = [];
        const map = {};

        // 构建映射关系
        for (const node of data) {
          map[node.id] = { ...node, children: [] };
        }

        // 构建树结构
        for (const node of Object.values(map)) {
          if (node.pid === null) {
            result.push(
              getItem(
                node.menuName,
                node.id,
                node.icon,
                node.children,
                node.path,
                node.orderNum,
              ),
            );
          } else if (map[node.pid]) {
            map[node.pid].children.push(
              getItem(
                node.menuName,
                node.id,
                node.icon,
                node.children,
                node.path,
                node.orderNum,
              ),
            );
          }
        }

        // 递归处理子节点并排序
        const processChildren = (nodes) => {
          if (!nodes || nodes.length === 0) return null;

          // 递归处理每个子节点
          nodes.forEach((node) => {
            if (node.children && node.children.length > 0) {
              // 先处理子节点的子节点
              processChildren(node.children);
            } else {
              node.children = null;
            }
          });

          // 当前层级按 order_num 排序
          return nodes.sort((a, b) => (a.order_num || 0) - (b.order_num || 0));
        };

        // 处理并排序根节点
        return processChildren(result);
      };

      const menuTree = handleMenuTree(this.menu);
      this.menuTree = menuTree;
    },

    reset() {
      this.$reset();
      sessionStorage.removeItem("menu");
    },
  },
  persist: {
    enabled: true,
    storage: sessionStorage,
  },
});

export default useMenu;
